package cn.ijero.contactlist.main

import android.widget.ImageView
import android.widget.RadioButton
import cn.ijero.contactlist.R
import cn.ijero.contactlist.database.table.Contact
import cn.ijero.contactlist.ext.dp
import coil.load
import coil.transform.RoundedCornersTransformation
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder

class ContactListAdapter : BaseMultiItemQuickAdapter<Contact, BaseViewHolder>() {

    private val selected = mutableListOf<Int>()

    init {
        addItemType(Contact.TYPE_HEADER, R.layout.item_header)
        addItemType(Contact.TYPE_ITEM, R.layout.item_contact)
    }

    override fun convert(holder: BaseViewHolder, item: Contact) {
        when (item.itemType) {
            Contact.TYPE_HEADER -> {
                holder.setText(R.id.title_text_view, item.name)
            }
            else -> {
                holder.getView<ImageView>(R.id.avatar_image_view).load(item.avatar) {
                    transformations(RoundedCornersTransformation(4.dp))
                    placeholder(R.mipmap.ic_launcher)
                }
                holder.setText(R.id.name_text_view, item.name)
                holder.getView<RadioButton>(R.id.radio_button).isChecked =
                    selected.contains(holder.bindingAdapterPosition)
            }
        }
    }

    override fun convert(holder: BaseViewHolder, item: Contact, payloads: List<Any>) {
        if (payloads.isNotEmpty()){
            holder.getView<RadioButton>(R.id.radio_button).isChecked =
                selected.contains(holder.bindingAdapterPosition)
        }
    }

    fun selected(index: Int) {
        if (this.selected.contains(index)) {
            this.selected.remove(index)
        } else {
            this.selected.add(index)
        }
        notifyItemChanged(index, true)
    }
}